#include "chess_window.h"
#include <QDesktopWidget>
#include <QMessageBox>
#include <QCloseEvent>
#include <QBitmap>


int const ChessWindow::M_WIDTH = 800;
int const ChessWindow::M_HEIGHT = 600;
int const ChessWindow::M_BOARD_WIDTH = 520;
int const ChessWindow::M_BOARD_HEIGHT = 576;

ChessWindow::ChessWindow(void)
{
    QPixmap bg(QString::fromUtf8(":/images/board.bmp"));
    QPalette palette;

    // 设置界面风格
    setupUi(this);

    // 设置窗口大小、位置
    setWindowFlags(windowFlags()& ~Qt::WindowMaximizeButtonHint);
    setFixedSize(M_WIDTH, mainMenuBar->height() + M_HEIGHT);
    move((QApplication::desktop()->width() - width()) / 2,
         (QApplication::desktop()->height() - height()) / 2);

    // 设置棋盘
    palette.setBrush(board->backgroundRole(), QBrush(bg));
    board->setFixedSize(M_BOARD_WIDTH, M_BOARD_HEIGHT);
    board->setAutoFillBackground(true);
    board->setPalette(palette);

    QPixmap chs(QString::fromUtf8(":/images/bk.bmp"));
    QPalette   palette2;
    palette2.setBrush(m_chesses[0].backgroundRole(),QBrush( chs ));
    m_chesses[0].setPalette(palette2);
    m_chesses[0].setMask(chs.createMaskFromColor(QColor(0, 255, 0)));
    m_chesses[0].setAutoFillBackground( true );
    boardLayout->addWidget(&m_chesses[0], 1, 1);


    QPixmap chs3(QString::fromUtf8(":/images/bk.bmp"));
    QPalette   palette3;
    palette3.setBrush(m_chesses[3].backgroundRole(),QBrush( chs3 ));
    m_chesses[3].setPalette(palette3);
    m_chesses[3].setMask(chs3.createMaskFromColor(QColor(0, 255, 0)));
    m_chesses[3].setAutoFillBackground( true );
    boardLayout->addWidget(&m_chesses[3], 1, 3);
}

void ChessWindow::closeEvent(QCloseEvent *pEvent)
{
    // "警告"
    const QString title(QString::fromUtf8(A_WARNING));

    // "确定关闭？"
    const QString info(QString::fromUtf8(A_CONFIRM)
                           + QString::fromUtf8(A_CLOSE)
                           + QString::fromUtf8(A_QUESTION));

    QMessageBox closeConfirm(this);
    QAbstractButton *pOk = NULL;
    QAbstractButton *pCancle = NULL;
    QPushButton *pDefault = NULL;

    closeConfirm.setIcon(QMessageBox::Question);
    closeConfirm.setWindowTitle(title);
    closeConfirm.setText(info);
    pOk = closeConfirm.addButton(QString::fromUtf8(A_CONFIRM),
                                 QMessageBox::ActionRole);
    pCancle = closeConfirm.addButton(QString::fromUtf8(A_CANCEL),
                                     QMessageBox::ActionRole);
    pDefault = dynamic_cast<QPushButton *>(pCancle);
    if (NULL != pDefault) {
        closeConfirm.setDefaultButton(pDefault);
    }

    static_cast<void>(closeConfirm.exec());

    if (closeConfirm.clickedButton() == pOk) {
        pEvent->accept();
    } else if (closeConfirm.clickedButton() == pCancle) {
        pEvent->ignore();
    } else {
        Q_ASSERT(0);
    }

    return;
}
